package com.pic4493.app;

import java.util.ArrayList;

import org.json.JSONArray;

import android.R.integer;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.pic4493.adapter.AdpList_PicList;
import com.pic4493.base.BaseUI;
import com.pic4493.comm.PubConst;
import com.pic4493.comm.Session;
import com.pic4493.entities.DJson;
import com.pic4493.entities.EAlbum;
import com.pic4493.entities.ESubscribe;
import com.pic4493.net.NetClientJ;
import com.pic4493.utils.UtiDialog;
import com.ppcodes.imageloader.core.display.FakeBitmapDisplayer;
import com.ppcodes.views.pulltorefresh.library.PullToRefreshBase;
import com.ppcodes.views.pulltorefresh.library.PullToRefreshBase.Mode;
import com.ppcodes.views.pulltorefresh.library.PullToRefreshBase.State;
import com.ppcodes.views.pulltorefresh.library.PullToRefreshStaggeredGridView;
import com.ppcodes.views.staggeredgridview.StaggeredGridView;

/**
 * 相册列表
 * 
 * @author Administrator
 * 
 */
public class UIPicList extends BaseUI implements OnClickListener
{

   private String mSortType = PubConst.AlbumSortType.DEFAULT;
   private String mSubjectId;
   private String mTitle;
   private String mDescribe;

   private ImageView mImgSub;
   private PullToRefreshStaggeredGridView mGridView;
   private LayoutInflater mInflater;
   private int mCurrentIndex = 1;
   private int mPageCount;
   private ArrayList<Integer> mLoadedIndex;
   private LinearLayout mLaySortNew;
   private LinearLayout mLaySortLove;
   private LinearLayout mLaySortHot;
   private LinearLayout mLaySortMore;

   private TextView mTxtTopTitle;
   private TextView mTxtTopDescribe;

   private boolean mIsPullToRefresh = false;
   private ArrayList<EAlbum> mList;
   private AdpList_PicList mAdpPic;

   private void initView()
   {
	  mInflater = LayoutInflater.from(mContext);
	  mImgSub = (ImageView) findViewById(R.id.uipiclist_img_topsub);
	  mLaySortHot = (LinearLayout) findViewById(R.id.uipiclist_lay_hot);
	  mLaySortLove = (LinearLayout) findViewById(R.id.uipiclist_lay_love);
	  mLaySortNew = (LinearLayout) findViewById(R.id.uipiclist_lay_new);
	  mLaySortMore = (LinearLayout) findViewById(R.id.uipiclist_lay_more);

	  mTxtTopTitle = (TextView) findViewById(R.id.uipiclist_txt_toptitle);
	  mTxtTopTitle.setText(mTitle);
	  mTxtTopDescribe = (TextView) findViewById(R.id.uipiclist_txt_topdec);
	  mTxtTopDescribe.setText(mDescribe);

	  mGridView = (PullToRefreshStaggeredGridView) findViewById(R.id.uipiclist_list);
	  View footView = mInflater.inflate(R.layout.layout_loading_footer, null);// 加载时显示的
	  mGridView.getRefreshableView().setFooterView(footView);
	  mGridView.getRefreshableView().setColumnCount(2);
	  mGridView.setMode(Mode.PULL_FROM_START);

   }

   private void initEvent()
   {
	  mImgSub.setOnClickListener(this);
	  mLaySortHot.setOnClickListener(this);
	  mLaySortLove.setOnClickListener(this);
	  mLaySortNew.setOnClickListener(this);
	  mLaySortMore.setOnClickListener(this);

	  // 下拉触发的事件
	  mGridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<StaggeredGridView>()
	  {
		 @Override
		 public void onRefresh(PullToRefreshBase<StaggeredGridView> refreshView)
		 {
			mIsPullToRefresh = true;
			initData();
		 }
	  });
	  // 滑到最下面加载更多数据的事件
	  mGridView.setOnLoadmoreListener(new StaggeredGridView.OnLoadmoreListener()
	  {
		 @Override
		 public void onLoadmore()
		 {
			if (mCurrentIndex < mPageCount)
			{
			   loadMoreData();
			}
			else
			{
			   mGridView.onLoadComplete();
			   mAdpPic.notifyDataSetChanged();
			   UtiDialog.getInstance().ShowToastInfoShort(mContext, "没有更多的数据了");
			}
		 }
	  });

	  mAdpPic = new AdpList_PicList(mContext, new AdpList_PicList.OnClickEvent()
	  {
		 @Override
		 public void Do(int position, View v)
		 {
			EAlbum album = (EAlbum) mAdpPic.getItem(position);
			Intent intent = new Intent();
			intent.setClass(UIPicList.this, UIPics.class);
			intent.putExtra(PubConst.Intent_Key.AlbumId, album.getId());
			intent.putExtra(PubConst.Intent_Key.Describe, album.getName());
			startActivity(intent);
		 }
	  });

   }

   private void initData()
   {
	  mCurrentIndex = 1;
	  mAdpPic.cleanData();
	  mLoadedIndex = new ArrayList<Integer>();
	  executeAsyncTask("initData");
   }

   private void loadMoreData()
   {
	  mCurrentIndex++;
	  if (!isLoadedThisPage(mCurrentIndex))// 此页没有被加载过
	  {
		 executeAsyncTask("loadData");
	  }
   }

   private boolean isLoadedThisPage(int index)
   {
	  if (-1 == mLoadedIndex.indexOf(index))
	  {
		 return false;
	  }
	  else
	  {
		 return true;
	  }
   }

   @Override
   protected void onCreate(Bundle savedInstanceState)
   {
	  setContentView(R.layout.uipiclist);
	  super.onCreate(savedInstanceState);
	  setTitle("相册列表");

	  mSubjectId = getIntent().getStringExtra(PubConst.Intent_Key.SubId);
	  mTitle = getIntent().getStringExtra(PubConst.Intent_Key.Name);
	  mDescribe = getIntent().getStringExtra(PubConst.Intent_Key.Describe);

	  initView();
	  initEvent();
	  initData();
   }

   @Override
   public void onClick(View v)
   {
	  switch (v.getId())
	  {
		 case R.id.uipiclist_img_topsub:
			if (Session.getInstance().isLogin())
			{
			   executeAsyncTask("sub");
			}
			else
			{
			   Intent uiIntent = new Intent();
			   uiIntent.setClass(mContext, UISignUp.class);
			   startActivityForResult(uiIntent, PubConst.ActivityJump.LOGIN);
			}
			break;
		 case R.id.uipiclist_lay_new:
			mSortType = PubConst.AlbumSortType.DATELINE;
			initData();
			break;
		 case R.id.uipiclist_lay_love:
			mSortType = PubConst.AlbumSortType.CLICK;
			initData();
			break;
		 case R.id.uipiclist_lay_hot:
			mSortType = PubConst.AlbumSortType.COMMENT;
			initData();
			break;
		 case R.id.uipiclist_lay_more:
			Intent intent = new Intent(mContext, UISetting.class);
			startActivity(intent);
			break;
	  }
   }

   @Override
   public void onAsyncTaskStart(String taskName, Object[] params)
   {
	  if ("sub".equals(taskName))
	  {
		 UtiDialog.getInstance().ShowLoadingDialogNoTitle(mContext, "请稍候");
	  }
	  else if ("initData".equals(taskName))
	  {
		 if (!mIsPullToRefresh)
		 {
			UtiDialog.getInstance().ShowLoadingDialogNoTitle(mContext, "加载中...");
		 }
	  }
   }

   @Override
   public Object onAsyncTaskInBackground(String taskName, Object[] params) throws Exception
   {
	  if ("sub".equals(taskName))
	  {
		 return NetClientJ.AddSubscribe(params[0].toString());
	  }
	  else if ("loadData".equals(taskName) || "initData".equals(taskName))
	  {
		 return NetClientJ.GetAlbumsBySubjectId(mSubjectId, mSortType, mCurrentIndex);
	  }
	  return null;
   }

   @Override
   public void onAsyncTaskEnd(String taskId, String taskName, Object[] params, Object result)
   {
	  UtiDialog.getInstance().DismissLoadingDialog();
	  try
	  {
		 if (result != null)
		 {
			DJson data = (DJson) result;
			if (!data.getHead().hasError())
			{
			   if (taskName.equals("sub"))
			   {
				  UtiDialog.getInstance().ShowToastInfoShort(mContext, "添加订阅成功");
			   }
			   else if ("initData".equals(taskName) || "loadData".equals(taskName))
			   {
				  mPageCount = data.getHead().getPageCount();
				  JSONArray albums = data.getBody().optJSONArray("special");
				  if (albums != null && albums.length() > 0)
				  {
					 mList = new ArrayList<EAlbum>();
					 EAlbum album = null;
					 for (int i = 0; i < albums.length(); i++)
					 {
						album = new EAlbum();
						album.setId(albums.optJSONObject(i).optString("aid"));
						album.setName(albums.optJSONObject(i).optString("name"));
						album.setCoverUrl(albums.optJSONObject(i).optString("cover_thum"));
						album.setCoverHeight(albums.optJSONObject(i).optInt("thum_height", 0));
						album.setCoverWidth(albums.optJSONObject(i).optInt("thum_with", 0));
						album.setContent(albums.optJSONObject(i).optString("describe"));
						mList.add(album);
					 }

					 mAdpPic.addItem(mList);
					 if ("initData".equals(taskName))
					 {
						mGridView.setAdapter(mAdpPic);
					 }
					 if (mPageCount == 1)// 如果只有一页数据,也不显示最下面的loading
					 {
						mGridView.onLoadComplete();
					 }
					 mAdpPic.notifyDataSetChanged();
					 mLoadedIndex.add(mCurrentIndex);// 将此页加入已读页码列表
				  }
				  else
				  // 没有数据
				  {
					 if (mList.size() == 0)
					 {
						UtiDialog.getInstance().ShowToastInfoShort(mContext, "暂无数据");
						finish();
					 }
					 else
					 {
						mGridView.onLoadComplete();
						mAdpPic.notifyDataSetChanged();
						if (mAdpPic.getCount() == 0)
						{
						   UtiDialog.getInstance().ShowOKAlertDialogEX(mContext, "提示", "本专题暂无数据", new DialogInterface.OnClickListener()
						   {
							  @Override
							  public void onClick(DialogInterface dialog, int which)
							  {
								 finish();
							  }
						   });
						}
					 }
				  }
				  if (mIsPullToRefresh)
				  {
					 mGridView.onRefreshComplete();
					 mIsPullToRefresh = false;
				  }
			   }
			}
			else
			{
			   UtiDialog.getInstance().ShowToastInfoShort(mContext, data.getHead().getRspMsg());
			}
		 }
		 else
		 {
			UtiDialog.getInstance().ShowToastInfoShort(mContext, "网络异常请稍候再试");
		 }
	  }
	  catch (Exception e)
	  {
		 Log.d("ERROR", "UIPicList_onAsyncTaskEnd(taskId, taskName, params, result) " + e);
	  }
   }

}
